package com.jqb.hibernatebbs.service;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.Transaction;

import com.jqb.hibernatebbs.pojo.Bbsmsg;
import com.jqb.hibernatebbs.util.SessionHandler;

public class BbsMsgService {

	/**
	 * 查询所有帖子
	 */
	@SuppressWarnings("unchecked")
	public List<Bbsmsg> getMsgs() {
		Session session = SessionHandler.getSession();
		Transaction ts = null;
		List<Bbsmsg> msgList = null;
		try {
			ts = session.beginTransaction();
			
			String hql = "from Bbsmsg order by id desc";
			msgList = session.createQuery(hql).list();
			ts.commit();
		} catch (Exception e) {
			if (ts != null) {
				ts.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}
		return msgList;
	}
	/**
	 * 增加帖子
	 * */
	public boolean addMsg(Bbsmsg bbsmsg) {
		boolean flag = false;
		Session session = SessionHandler.getSession();
		Transaction ts = null;
		try {
			ts = session.beginTransaction();
			session.save(bbsmsg);
			ts.commit();
			flag = true;
		} catch (Exception e) {
			flag = false;
			if (ts != null) {
				ts.rollback();
			}
			throw new RuntimeException(e.getMessage());
		} finally {
			if (session != null) {
				session.close();
			}
		}

		return flag;
	}

	public static BbsMsgService newInstance() {
		return new BbsMsgService();
	}
}
